<template>
  <div class="app-container">
    <div class="wise-crud">
      <div class="table-show">
        <div class="operation-block">
          <el-row class="oper-btn" :gutter="10">
            <el-col :span="16">
              <el-button type="primary" @click="handleAdd"><i class="el-icon-plus" />添加</el-button>
            </el-col>
            <el-col :span="8" class="text-right">
              <el-input v-model="search.key" placeholder="请输入姓名" class="input-with-select">
                <el-button slot="append" icon="el-icon-search" @click="getTableData" />
              </el-input>
            </el-col>
          </el-row>
        </div>
        <div class="wise-table">
          <el-table :data="tableData" border highlight-current-row>
            <el-table-column type="index" width="50" />
            <el-table-column label="头像">
              <template slot-scope="scope">
                <template v-if="scope.row.userInfo">
                  <el-image style="width: 50px; height: 50px" :src="scope.row.userInfo.picture | imgPath('sm')"
                    fit="cover">
                    <div slot="error" class="image-slot">
                      <img src="~@/assets/img/default.png" style="width: 100%; height: 100%">
                    </div>
                  </el-image>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="姓名">
              <template slot-scope="scope">
                <template v-if="scope.row.userInfo">
                  {{ scope.row.userInfo.username }}
                </template>
              </template>
            </el-table-column>
            <el-table-column label="联系电话">
              <template slot-scope="scope">
                <template v-if="scope.row.userInfo">
                  {{ scope.row.userInfo.phone }}
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column label="所属企业">
              <template slot-scope="scope">
                <template v-if="scope.row.userInfo">
                  {{ scope.row.userInfo.entName }}
                </template>
              </template>
            </el-table-column>
            <el-table-column label="所管项目">
              <template slot-scope="scope">
                <template v-if="scope.row.projectInfo">
                  {{ scope.row.projectInfo.name }}
                </template>
              </template>
            </el-table-column> -->
            <el-table-column label="职务">
                <template slot-scope="scope">
                  <template v-if="scope.row.professionList">
                    {{ scope.row.userInfo.wechat }}
                  </template>
                </template>
              </el-table-column>
            <el-table-column label="人员编号">
              <template slot-scope="scope">
                <template v-if="scope.row.userInfo">
                  {{ scope.row.userInfo.serialNum }}
                </template>
              </template>
            </el-table-column>
            <!-- <el-table-column label="角色岗位">-->
            <!--              <template slot-scope="scope">-->
            <!--                <template v-if="scope.row.userMemeberRoleList && scope.row.userMemeberRoleList.length">-->
            <!--                  {{ scope.row.userMemeberRoleList.map(item=>item.roleName).join('、') }}-->
            <!--                </template>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
            <!--            <el-table-column label="工种">-->
            <!--              <template slot-scope="scope">-->
            <!--                <template v-if="scope.row.professionList && scope.row.professionList.length">-->
            <!--                  {{ scope.row.professionList.map(item=>item.professionName).join('、') }}-->
            <!--                </template>-->
            <!--              </template>-->
            <!--            </el-table-column> -->
            <el-table-column label="操作" width="300">
              <template slot-scope="scope">
                <el-button type="primary" size="small" round @click.native.prevent="settingHandle(scope.row)">设置
                </el-button>
                <el-button type="info" size="small" round @click.native.prevent="editUserInfoHandle(scope.row)">编辑
                </el-button>
                <el-button type="danger" size="small" round @click.native.prevent="removeHandle(scope.row)">移除
                </el-button>
                <el-button type="warning" size="small" class="activeBtn" round
                  @click.native.prevent="initHandle(scope.row)">重置密码</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="page-block">
            <pagination :background="true" layout="total,prev, pager, next" :total="ts" :page.sync="page.p"
              :limit.sync="page.ps" @pagination="getTableData" />
          </div>
        </div>
      </div>
      <el-dialog ref="drawer" title="添加成员" :visible.sync="drawer" close-on-press-escape destroy-on-close>
        <div class="draw-body" style="padding: 0 50px">
          <wise-form :columns="formItems1" v-if="drawer" :loading="loading" :old-object="obj.userInfo"
            @on-submit="submitHandle1" />
        </div>
      </el-dialog>
      <el-dialog ref="drawer1" title="设置岗位角色" :visible.sync="drawer1" close-on-press-escape destroy-on-close>
        <div class="draw-body">
          <el-form ref="ruleForm1" :model="setting.obj" :rules="setting.rules" :validate-on-rule-change="false"
            label-width="100px" label-suffix=":">
            <el-form-item label="设置岗位" prop="professionIds">
              <el-transfer v-model="setting.obj.professionIds" filterable :filter-method="filterMethod"
                filter-placeholder="请输入岗位名称" :titles="['岗位', '赋予岗位']" :data="setting.professionList"
                :props="{ key: 'id', label: 'name' }" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="settingSubmitForm('ruleForm1')">确定</el-button>
              <el-button @click="resetForm('ruleForm1')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
      <el-dialog ref="drawer2" title="编辑成员信息" :visible.sync="drawer2" close-on-press-escape destroy-on-close>
        <div class="draw-body">
          <wise-form :columns="formItems" :loading="loading" :old-object="obj.userInfo" @on-submit="submitHandle" />
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    postHandle
  } from '@/api'
  import Pagination from '@/components/Pagination/index'
  import {
    validPhone
  } from '@/utils/validate'
  import WiseForm from '@/components/Crud/Form/wiseForm'
  export default {
    name: 'MemberManage',
    components: {
      WiseForm,
      Pagination
    },
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!validPhone(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      }
      return {
        checked: false,
        checked1: false,
        checkList: ['选中且禁用', '复选框 A'],
        projectList: [],
        drawer: false,
        drawer1: false,
        drawer2: false,
        searchUserName: '',
        search: {
          key: '',
          fields: ['name', '']
        },
        tableData: [],
        page: {
          p: 1,
          ps: 10
        },
        ts: 0,
        obj: {
          spaceId: '',
          userInfo: {
            sex: null,
            icPicture: null,
            remark: null,
            picture: null,
            phone: null,
            id: null,
            ic: null,
            icPictureBack: null,
            age: null,
            email: null,
            username: null
          }
        },
        rules: {
          username: [{
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          }],
          phone: [{
              required: true,
              message: '请输入手机号码',
              trigger: 'blur'
            },
            {
              validator: validatePhone
            }
          ]
        },
        setting: {
          id: '',
          professionList: [],
          obj: {
            professionIds: []
          },
          rules: {}
        },
        filterMethod(query, item) {
          return item.name.indexOf(query) > -1
        },
        loading: false,
        formItems1: [{
            label: '个人头像',
            prop: 'picture',
            type: 'file',
            rules: [{
              required: true,
              message: '请选个人头像',
              trigger: 'blur'
            }]
          },
          {
            label: '真实姓名',
            prop: 'username',
            type: 'text',
            maxlength: 20,
            rules: [{
              required: true,
              message: '请输入真实姓名',
              trigger: 'blur'
            }],
            placeholder: '请输入真实姓名'
          },
          {
            label: '年龄',
            prop: 'age',
            type: 'number',
            min: 18,
            placeholder: '请输入年龄'
          },
          {
            label: '性别',
            prop: 'sex',
            type: 'radio',
            dataDic: 'sex'
          },
          {
            label: '手机号',
            prop: 'phone',
            type: 'text',
            maxlength: 11,
            rules: [{
                required: true,
                message: '请输入登录手机号',
                trigger: 'blur'
              },
              {
                validator: validatePhone
              }
            ],
            placeholder: '请输入登录手机号'
          },
          {
            label: '血型',
            prop: 'nation',
            type: 'text',
            placeholder: '请输入血型'
          },
          {
            label: '职务',
            prop: 'wechat',
            type: 'text',
            placeholder: '请输入职务'
          },
          {
            label: '部门',
            prop: 'address',
            type: 'text',
            placeholder: '请输入部门'
          },
          {
            label: '邮箱',
            prop: 'email',
            type: 'text',
            placeholder: '请输入邮箱'
          },
          {
            label: '所属企业',
            prop: 'entName',
            type: 'text',
            placeholder: '请输入所属企业',
            use: ['add', 'view', 'edit'],
            rules: [{
              required: true,
              message: '请输入所属企业',
              trigger: 'blur'
            }]
          },
          {
            label: '人员编号',
            prop: 'serialNum',
            type: 'text',
            placeholder: '请输入人员编号',
            use: ['add', 'view', 'edit'],
            rules: [{
              required: true,
              message: '请输入人员编号',
              trigger: 'blur'
            }]
          },
        
         
        {
          label: '简介',
          prop: 'remark',
          type: 'textarea',
          placeholder: '请输入简介'
        }
        ],
        formItems: [{
            label: '个人头像',
            prop: 'picture',
            type: 'file',
            rules: [{
              required: true,
              message: '请选个人头像',
              trigger: 'blur'
            }]
          },
          {
            label: '真实姓名',
            prop: 'username',
            type: 'text',
            maxlength: 20,
            rules: [{
              required: true,
              message: '请输入真实姓名',
              trigger: 'blur'
            }],
            placeholder: '请输入真实姓名'
          },
          {
            label: '年龄',
            prop: 'age',
            type: 'number',
            min: 18,
            placeholder: '请输入年龄'
          },
          {
            label: '性别',
            prop: 'sex',
            type: 'radio',
            dataDic: 'sex'
          },
          {
            label: '手机号',
            prop: 'phone',
            type: 'text',
            disabled: true,
            maxlength: 11,
            rules: [{
                required: true,
                message: '请输入登录手机号',
                trigger: 'blur'
              },
              {
                validator: validatePhone
              }
            ],
            placeholder: '请输入登录手机号'
          }, {
            label: '血型',
            prop: 'nation',
            type: 'text',
            placeholder: '请输入血型'
          },
          {
            label: '职务',
            prop: 'wechat',
            type: 'text',
            placeholder: '请输入职务'
          },
          {
            label: '部门',
            prop: 'address',
            type: 'text',
            placeholder: '请输入部门'
          },
          {
            label: '邮箱',
            prop: 'email',
            type: 'text',
            placeholder: '请输入邮箱'
          },
         
        
          {
            label: '所属企业',
            prop: 'entName',
            type: 'text',
            placeholder: '请输入所属企业',
            use: ['add', 'view', 'edit'],
            rules: [{
              required: true,
              message: '请输入所属企业',
              trigger: 'blur'
            }]
          },
          {
            label: '人员编号',
            prop: 'serialNum',
            type: 'text',
            placeholder: '请输入人员编号',
            use: ['add', 'view', 'edit'],
            rules: [{
              required: true,
              message: '请输入人员编号',
              trigger: 'blur'
            }]
          },  {
            label: '简介',
            prop: 'remark',
            type: 'textarea',
            placeholder: '请输入简介'
          },
        ],
        userInfo: {
          sex: null,
          icPicture: null,
          remark: null,
          picture: null,
          phone: null,
          id: null,
          ic: null,
          icPictureBack: null,
          age: null,
          email: null,
          username: null
        },
        personalList: [],
        personalTotal: 0,
        personalSearch: {
          key: '',
          fields: ['username', 'phone', 'email']
        },
        persnoalPage: {
          p: 1,
          ps: 10
        },
        checkAll: false,
        isIndeterminate: false,
        memeber: {
          userIds: [],
          spaceId: ''
        },
        loading1: false,
        noMore: false,
        disabled: false,
        id: ''
      }
    },
    computed: {
      spaceId() {
        return this.$store.state.enterprise.entSpaceId
      },
      enterprise() {
        return this.$store.state.enterprise.obj
      }
    },
    created() {
      this.getTableData()
      this.obj.spaceId = this.spaceId
    },
    methods: {
      initHandle(row) {
        this.$confirm('您确定要重置该用户的密码?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            postHandle(
                '/api/v1/welder-uac-second/user-account-comb/init-password/' + row.userId, {}
              )
              .then((res) => {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: '操作失败'
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      handleAdd() {
        this.userInfo = {
          sex: null,
          icPicture: null,
          remark: null,
          picture: null,
          phone: null,
          id: null,
          ic: null,
          icPictureBack: null,
          age: null,
          email: null,
          username: null
        }
        this.drawer = true
      },
      getTableData() {
        const req = {
          d: {
            filters: [{
              field: 'spaceId',
              operator: 'EQUALS',
              value: this.spaceId
            }],
            fields: [{
                name: 'id'
              },
              {
                name: 'userInfo'
              },
              {
                name: 'spaceInfo'
              },
              {
                name: 'roleList'
              },
              {
                name: 'projSpaceInfoList'
              }
            ],
            page: this.page,
            retPage: true,
            search: this.search
          },
          // obj: {
          //   username: this.searchUserName
          // }
        }
        postHandle(
          '/api/v1/welder-uac-second/space-user-member-comb/get-list',
          req
        ).then((response) => {
          this.tableData = response.result
          this.ts = response.page.ts
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            postHandle(
              '/api/v1/welder-uac-second/space-organization-member-comb/create-member', {
                obj: this.obj
              }
            ).then((response) => {
              this.getTableData(this.obj.spaceId)
              this.getTableData()
              this.drawer = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },

      settingHandle(row) {
        this.drawer1 = true
        this.setting.id = row.id
        if (row.professionList && row.professionList.length > 0) {
          this.setting.obj.professionIds = row.professionList.map(
            (item) => item.professionId
          )
        } else {
          this.setting.obj.professionIds = []
        }
        this.getJobList()
      },

      getJobList() {
        const req = {
          d: {
            filters: [{
                field: 'spaceId',
                operator: 'EQUALS',
                value: this.spaceId
              },
              {
                field: 'level',
                operator: 'NE',
                value: 1
              }
            ],
            fields: [],
            page: {
              p: 1,
              ps: 9999
            }
          }
        }
        postHandle('/api/v1/welder-uac-second/base-profession-comb/list', req).then(
          (response) => {
            this.setting.professionList = response.result
          }
        )
      },

      settingSubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            postHandle(
                `/api/v1/welder-uac-second/space-organization-member-comb/configure-member-privilege/${this.setting.id}`, {
                  obj: this.setting.obj
                }
              )
              .then((response) => {
                this.getTableData(this.obj.spaceId)
                this.drawer1 = false
              })
              .catch((error) => {
                this.loading = false
                const data = error.response.data
                for (const key in data) {
                  this.$message.error(this.$t(data[key]))
                }
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

      deleteObjectById(id) {
        postHandle(
            '/api/v1/welder-uac-second/space-user-member-comb/remove-space-user-member/' +
            id, {}
          )
          .then((response) => {
            this.getTableData(this.obj.spaceId)
            this.$message({
              type: 'success',
              message: '移除成功!'
            })
          })
          .catch((error) => {
            this.loading = false
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(data[key]))
            }
          })
      },
      getUserInfoById(id) {
        postHandle(`/api/v1/welder-uac-second/user-information/show/${id}`, {}).then(
          (response) => {
            this.obj.userInfo = response.result
          }
        )
      },
      editUserInfoHandle(row) {
        this.getUserInfoById(row.userInfo.id)
        this.id = row.id
        this.drawer2 = true
      },
      submitHandle1(object) {
        this.loading = true
        let url = '/api/v1/welder-uac-second/space-user-member-comb/create'
        postHandle(url, {
            obj: {
              spaceId: this.spaceId,
              userInfo: object
            }
          })
          .then((response) => {
            this.$message('操作成功')
            this.loading = false
            this.drawer = false
            this.getTableData()
          })
          .catch((error) => {
            this.loading = false
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(data[key]))
            }
          })
      },
      submitHandle(object) {
        this.loading = true
        let url = '/api/v1/welder-uac-second/space-user-member-comb/update/' + this.id
        postHandle(url, {
            obj: {
              spaceId: this.spaceId,
              userInfo: object
            }
          })
          .then((response) => {
            this.$message('操作成功')
            this.loading = false
            this.drawer2 = false
            this.getTableData()
          })
          .catch((error) => {
            this.loading = false
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(data[key]))
            }
          })
      },
      removeHandle(row) {
        this.$confirm('您确定要移除该成员, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.deleteObjectById(row.id)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消移除'
            })
          })
      },
      getPersonal() {
        this.persnoalPage.p = 1
        let params = {
          d: {
            page: this.persnoalPage,
            search: this.personalSearch,
            retPage: true
          }
        }
        postHandle('/api/v1/welder-uac-second/user-information', params).then((res) => {
          this.personalList = res.result
          this.personalTotal = res.page.ts
          this.loading1 = false
          if (res.page.ts <= this.personalList.length) {
            this.noMore = true
            this.disabled = true
          } else {
            this.noMore = false
            this.disabled = false
            this.persnoalPage.p = this.persnoalPage.p + 1
          }
        })
      },
      load() {
        this.loading1 = true
        let params = {
          d: {
            page: this.persnoalPage,
            search: this.personalSearch,
            retPage: true
          }
        }
        this.noMore = true
        this.disabled = true
        postHandle('/api/v1/welder-uac-second/user-information', params).then((res) => {
          this.isIndeterminate = true
          this.checkAll = false
          this.personalList = this.personalList.concat(res.result)
          this.personalTotal = res.page.ts
          this.loading1 = false
          if (this.personalTotal <= this.personalList.length) {
            this.noMore = true
            this.disabled = true
          } else {
            this.noMore = false
            this.disabled = false
            this.persnoalPage.p = this.persnoalPage.p + 1
          }
        })
      }
    }
  }
</script>

<style>
  .el-transfer .el-checkbox {
    display: block;
  }
</style>